import React, { useRef, useState, useEffect } from 'react'
import { Modal, Form, Input, message, Radio, DatePicker, InputNumber } from 'antd'
import { awaitWrap, strToNum } from '@js/tool'
import { submitFiles } from '@js/request'
import { addRequest, getRequest, updateRequest } from './ajax'
import style from './Index.module.less'
import moment from 'moment'
// import CheckboxAll from '@components/CheckboxAll/Index'
import Upload from '@components/Upload/Index'

const { Item } = Form
// const options = ['仲裁机构', '当事人', '仲裁员'].map(li => ({ label: li, value: li }))

async function getHandle (id, formRef, setThumbnail) {
  const c = formRef.current
  const h = message.loading('加载中')
  const [e, d] = await awaitWrap(getRequest(id))
  h()
  if (e === null && d !== null) {
    if (d.thumbnail instanceof Object) {
      setThumbnail([d.thumbnail].map(li => {
        li.name = li.original_filename || li.filename
        return li
      }))
    }
    if (d.file instanceof Array && d.file.length > 0) {
      d.file.map(li => {
        li.name = li.original_filename || li.filename
        return li
      })
    }
    if (typeof d.visible_type === 'string' && d.visible_type.length > 0) {
      d.visible_type = d.visible_type.split(',')
    } else {
      d.visible_type = []
    }
    d.expiry_datetime = strToNum(d.expiry_datetime)
    d.release_datetime = strToNum(d.release_datetime)
    if (d.expiry_datetime) {
      d.expiry_datetime = moment(d.expiry_datetime * 1000)
    }
    if (d.release_datetime) {
      d.release_datetime = moment(d.release_datetime * 1000)
    }
    c.setFieldsValue(d)
  }
}

async function submitHandle (form, thumbnail, callback) {
  const hide = message.loading('提交中', 120)
  let fn = addRequest
  if (form.id) {
    fn = updateRequest
  }
  const keys = Object.keys(form)
  keys.forEach(k => {
    if (!form[k]) {
      form[k] = null
    }
  })
  if (thumbnail.length > 0) {
    const [e, d] = await awaitWrap(submitFiles(thumbnail))
    if (e) {
      hide()
    }
    form.thumbnailid = d
  }
  if (form.file.length > 0) {
    const [e, d] = await awaitWrap(submitFiles(form.file))
    if (e) {
      hide()
    }
    form.fileid = d
  }
  delete form.file
  delete form.thumbnail
  // if (form.visible_type instanceof Array && form.visible_type.length) {
  //   form.visible_type = form.visible_type.join(',')
  // } else {
  //   form.visible_type = null
  // }
  form.visible_type = '当事人'
  if (form.release_datetime && form.release_datetime instanceof moment) {
    form.release_datetime = Math.floor(form.release_datetime.valueOf() / 1000)
  }
  if (form.expiry_datetime && form.expiry_datetime instanceof moment) {
    form.expiry_datetime = Math.floor(form.expiry_datetime.valueOf() / 1000)
  }
  const [e] = await awaitWrap(fn(form))
  hide()
  if (e === null) {
    callback()
  }
}

function Main ({ visible, data, hide = () => {}, refreshFn = () => {} }) {
  const formRef = useRef(null)
  const [thumbnail, setThumbnail] = useState([])
  useEffect(() => {
    const c = formRef.current
    if (c) {
      if (visible) {
        if (data) {
          getHandle(data.id, formRef, setThumbnail)
        }
      } else {
        c.resetFields()
      }
    }
  }, [visible, data, formRef])
  return (
    <Modal width='1000px' open={visible} title={`${data ? '编辑文书' : '新增文书'}`} onCancel={() => { hide() }} onOk={() => formRef.current.submit()} maskClosable={false}>
      <Form ref={formRef} labelCol={{ flex: '80px' }} initialValues={{ status: '发布' }} onFinish={(d) => { submitHandle(d, thumbnail, () => { refreshFn(); hide() }) }}>
        <Item name='id' noStyle><span /></Item>
        <Item label='标题' name='title' rules={[{ required: true, message: '标题不能为空' }]}>
          <Input placeholder='请输入' allowClear />
        </Item>
        {/* <Item label='可见类型' name='visible_type'>
          <CheckboxAll options={options} />
        </Item> */}
        <Item label='状态' name='status'>
          <Radio.Group>
            <Radio value='发布'>发布</Radio>
            <Radio value='草稿'>未发布</Radio>
          </Radio.Group>
        </Item>
        <Item label='发布日期' name='release_datetime'>
          <DatePicker placeholder='请选择' showTime allowClear className={style.full} />
        </Item>
        <Item label='排序' name='orderno'>
          <InputNumber placeholder='请输入' allowClear className={style.full} />
        </Item>
        <Item name='file' label='附件'>
          <Upload maxLength={1} />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
